/**
 * 资质类型、证书专业以及证书级别三级联动判断
 * @param obj 证书类型
 * @param generalType 大类型(证书或资质)编码
 * @param type 联动类型  0-查询证书类型 1-根据证书类型查询证书专业  2-不加载证书级别
 * @param isLoadLevel 是否加载证书级别 0-加载 1-不加载
 * @param certificateSpecialtyObj 证书专业
 * @param certificateLevelObj 证书级别
 */
function loadCertificateType(length, obj, generalType, type, certificateSpecialtyObj, isLoadLevel, certificateLevelObj) {
    if (checkIsEmpty(type)) {
        DGG.Errors("请传入联动类型！");
        return false;
    }
    if (type === 0) {
        $(obj).find("option").remove();
        $(obj).append("<option value=''>请选择</option>");
        $.post(sysInfo.basePath + "/zs/certificate_type/get_certificate_type.do", {
            parentId: 0,
            generalType: generalType
        }, function (result) {
            if (result.code == 0) {
                $.each(result.data, function (i, item) {
                    $(obj).append("<option value='" + item.id + "' data-level='" + item.certificateLevel + "'>" + item.certificateName + "</option>");
                });
            } else {
                DGG.Errors(result.msg);
            }
        });
        $(obj).select2({
            placeholder: "请选择",
            allowClear: true,
            width: length,
            language: "zh-CN"
        });
    } else if (type === 1) {
        // 验证证书类型是否已经选择
        var certificateTypeId = $(obj + " option:selected").val();
        if (!checkIsEmpty(certificateTypeId)) {
            $(certificateSpecialtyObj).find("option").remove();
            $.post(sysInfo.basePath + "/zs/certificate_type/get_certificate_type.do", {
                parentId: certificateTypeId,
                generalType: generalType
            }, function (result) {
                if (result.code == 0) {
                    $(certificateSpecialtyObj).val('').trigger('change');
                    $(certificateSpecialtyObj).append("<option value=''>请选择</option>");
                    $.each(result.data, function (i, item) {
                        $(certificateSpecialtyObj).append("<option value='" + item.id + "' data-level='" + item.certificateLevel + "'>" + item.certificateName + "</option>");
                    });
                } else {
                    DGG.Errors(result.msg);
                }
            });
            $(certificateSpecialtyObj).select2({
                placeholder: "请选择",
                allowClear: false,
                width: length,
                language: "zh-CN"
            });

            if (!checkIsEmpty(isLoadLevel) && isLoadLevel === 0) {
                // 加载证书等级
                var levelStrs = $(obj + " option:selected").attr("data-level");
                $(certificateLevelObj).find("option").remove();
                $(certificateLevelObj).append("<option value=''>请选择</option>");
                var levels;
                if (!checkIsEmpty(levelStrs)) {
                    levels = levelStrs.split(",");
                }
                if (checkIsEmpty(levels)) {
                    $(certificateLevelObj).append("<option value=''>暂无等级</option>");
                } else {
                    $.post(sysInfo.basePath + '/zzsc/common/translate_code.do', {codes: levelStrs}, function (result) {
                        $.each(result.data, function (i, item) {
                            $(certificateLevelObj).append('<option value="' + item.code + '">' + item.name + '</option>');
                        });
                    });
                }
                $(certificateLevelObj).select2({
                    placeholder: "请选择",
                    allowClear: true,
                    width: length,
                    language: "zh-CN"
                });
            }

        } else {
            // DGG.Errors("请先选择证书类型！");
            $(certificateLevelObj).find("option").remove();
            $(certificateLevelObj).append("<option value=''>请选择</option>");
            $(certificateSpecialtyObj).find("option").remove();
            $(certificateSpecialtyObj).append("<option value=''>请选择</option>");
            return false;
        }
    }
}

/**
 * 验证证书专业长度
 * @param certificateTypeObj 证书类型obj
 * @param obj 证书专业obj
 */
function checkCertificateSpecialty(certificateTypeObj, obj) {
    var certificateTypeId = $(certificateTypeObj + " option:selected").val();
    if (!checkIsEmpty(certificateTypeId) || certificateTypeId == '') {
        var certificateSpecialtys = getVal(obj, 1);
        if (!checkIsEmpty(certificateSpecialtys) && certificateSpecialtys.length > 5) {
            DGG.Errors("最多只能选择五个证书专业！");
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

/**
 * 验证是否有查看事业部权限
 * @param obj 参考传值 $("#ddlRegType option")
 */
function checkHasSybAuth(obj) {
    var count = obj.length;
    if (checkIsEmpty(count) || count === 0) {
        return false;
    }
    return true;
}

/**
 * 加载证书类型、证书专业或者证书等级
 * @param obj          证书专业或者类型obj
 * @param objVal       证书专业或者类型的值
 * @param type       类型 0-证书类型 1-证书专业 2-证书等级 默认证书类型
 * @param generalType  大类型 资质或者证书
 * @param pid     证书类型传0  证书专业传父级id
 * @param certificateLevelObj 证书等级obj 需要加载证书等级时必传
 * @param certificateLevelVal 证书等级值 需要加载证书等级时必传
 */
function loadCertificateVal(obj, objVal, generalType, pid, type, certificateLevelObj, certificateLevelVal) {
    if (checkIsEmpty(type) || type === 0) {
        $(obj).find("option").remove();
        $.post(sysInfo.basePath + "/zs/certificate_type/get_certificate_type.do", {
            parentId: pid,
            generalType: generalType
        }, function (result) {
            if (result.code == 0) {
                var levelStrs = "";
                $.each(result.data, function (i, item) {
                    if (!checkIsEmpty(objVal) && objVal == item.id) {
                        levelStrs = item.certificateLevel;
                        $(obj).append("<option value='" + item.id + "' data-level='" + item.certificateLevel + "' SELECTED>" + item.certificateName + "</option>");
                    } else {
                        $(obj).append("<option value='" + item.id + "' data-level='" + item.certificateLevel + "'>" + item.certificateName + "</option>");

                    }
                });
                $(obj).select2({
                    placeholder: "请选择",
                    allowClear: true,
                    width: "100%",
                    language: "zh-CN"
                });
                // 加载证书等级
                $(certificateLevelVal).find("option").remove();
                var levels;
                if (!checkIsEmpty(levelStrs)) {
                    levels = levelStrs.split(",");
                }
                if (checkIsEmpty(levels)) {
                    $(certificateLevelVal).append("<option value=''>暂无等级</option>");
                } else {
                    $.post(sysInfo.basePath + '/zzsc/common/translate_code.do', {codes: levelStrs}, function (result) {
                        $.each(result.data, function (i, item) {
                            if (item.code === certificateLevelVal) {
                                $(certificateLevelObj).append('<option value="' + item.code + '" selected>' + item.name + '</option>');
                            } else {
                                $(certificateLevelObj).append('<option value="' + item.code + '">' + item.name + '</option>');
                            }
                        });
                    });
                }
            } else {
                DGG.Errors("系统错误，请联系管理员");
            }
        });
        $(certificateLevelObj).select2({
            placeholder: "请选择",
            allowClear: true,
            width: "100%",
            language: "zh-CN"
        });

    } else if (type == 1) {
        $(obj).find("option").remove();
        $(obj).append("<option value=''>请选择</option>");

        $.post(sysInfo.basePath + "/zs/certificate_type/get_certificate_type.do", {
            parentId: pid,
            generalType: generalType
        }, function (result) {
            if (result.code == 0) {
                $.each(result.data, function (i, item) {
                    $(obj).append("<option value='" + item.id + "' data-level='" + item.certificateLevel + "'>" + item.certificateName + "</option>");
                });
                $(obj).val(objVals).trigger('change');
            } else {
                DGG.Errors("系统错误，请联系管理员");
            }
        });
        var objVals = "";
        if (!checkIsEmpty(objVal)) {
            objVals = objVal.split(",");
        }
        $(obj).select2({
            placeholder: "请选择",
            allowClear: false,
            width: "100%",
            language: "zh-CN"
        });
    }


}

/**
 * 证书编号验重
 * @param obj
 * @param certificateType 证书类型  资质 普通证书
 * @param certificateId 证书id
 * @param isAdd 是否是新增证书 0-否 1-是
 */
function checkCertificateNo(obj, certificateType, certificateId, isAdd) {
    var dealResult = false;
    var productId = $('[name="productId"]').val();
    var no = $(obj).val();
    var params = {};
    params.certificateNo = no;
    if (!checkIsEmpty(certificateId)) {
        params.certificateId = certificateId;
    }
    if (!checkIsEmpty(certificateType)) {
        params.certificateType = certificateType;
        params.generalType = certificateType;
    }
    $.ajax({
        url: sysInfo.basePath + "/zs/base_credential/check_credential_no.do",
        data: params,
        type: "POST",
        dataType: "json",
        async: false,
        success: function (result) {
            if (result.code == 0) {
                if (checkIsEmpty(result.data)) {
                    dealResult = true;
                } else {
                    var scOrderId = $('[name="scOrderId"]').val();
                    if (!checkIsEmpty(isAdd) || isAdd == 1) {
                        var scOrderId = $("[name='scOrderId']").val();
                        DGG.Confire('该证书编号已经存在于退回人才证书中，是否将该证书恢复使用？', '操作提示', function () {
                            $.post(sysInfo.basePath + '/zs/general_credential/add_certificate_check.do', {productId: productId}, function (result) {
                                if (result.code == 0) {
                                    layer.closeAll();
                                    $.post(sysInfo.basePath + "/zs/general_credential/edit_return_credential_page.do", {certificateNo: no, productId: productId}, function (result) {
                                        var index = dgg.Open({
                                            type: 1,
                                            title: '退回证书入库',
                                            btn: ["确定", "取消"],
                                            content: result,
                                            area: '90%',
                                            yes: function () {
                                                // 验证页面字段
                                                if (!checkReturnCertificateFiled()) {
                                                    return false;
                                                }
                                                // 新增证书
                                                var params = $("#credentialForm").serializeObject();
                                                params.certificateSpecialtys = getTextVal('#certificateSpecialty');
                                                params.certificateSpecialty = getVal('#certificateSpecialty', 0);
                                                params.certificateTypeId = $("#certificateTypes option:selected").val();
                                                params.certificateType = $("#certificateTypes option:selected").html();
                                                params.baseId = $("#id").val();

                                                countGuidePrice(params, 2);
                                            }, end: function () {
                                                layer.closeAll("tips");
                                            }
                                        });
                                    }, 'html');

                                } else {
                                    DGG.Errors(result.msg);
                                }
                                DGG.loading('close');

                            }, 'json');

                        });
                    } else {
                        DGG.Alert_error('该证书编号已经存在于退回人才证书中,如需恢复使用，请重新下单！');
                        dealResult = false;
                    }

                }
            } else {
                DGG.Errors(result.msg);
                dealResult = false;
            }
        }
    });
    return dealResult;
}

/**
 * 验证证书指导价
 * @param params
 * @param type 验证类型 0 - 新增 1-修改 2-  重新入库 默认是
 */
function countGuidePrice(params, type) {
    $.post(sysInfo.basePath + "/zs/guide_price_config/count_guide_price.do", params, function (result) {
        if (result.code == 0) {
            if (!checkIsEmpty(result.data)) {
                var receiptPrice = $("#receiptPrice").val();
                var guidePrice = result.data.certificateGuidingPrice;
                if (receiptPrice > guidePrice) {
                    DGG.Confire('当前证书回收价格高于证书指导价格（' + fmtMoney(guidePrice) + '）,确认要继续吗？', '操作提示', function () {
                        if (checkIsEmpty(type) || type === 0) {
                            addCretificate(params);
                        } else {
                            returnCertificate(params);
                        }
                    })
                } else {
                    if (checkIsEmpty(type) || type === 0) {
                        addCretificate(params);
                    } else {
                        returnCertificate(params);
                    }
                }
            } else {
                if (checkIsEmpty(type) || type === 0) {
                    addCretificate(params);
                } else {
                    returnCertificate(params);
                }
            }

        } else {
            DGG.Errors(result.msg);
            DGG.loading('close');
            return false;
        }
    });
}

/**
 * 证书详情页面跳转
 * @param no 证书编号
 * @param id 证书id
 */
function credentialDetail(no, id) {
    window.top.addTab('证书详情:' + no, sysInfo.basePath +
        "/zs/general_credential/credential_detail.html?id=" + id);
}

/**
 * 证书需要验证的字段
 */
function checkAllCertificateFiled() {
    // 验证下拉选择框
    if (!checkDropDownChoice('#certificateType', $('#certificateType').next(), '')) return false;
    if (!checkDropDownChoice('#certificateSpecialtys', $('#certificateSpecialtys').next())) return false;
    if (!checkDropDownChoice('#certificateLevel', $('#certificateLevel').next())) return false;
    if (!checkDropDownChoice('#applicationScopes')) return false;
    if (!checkDropDownChoice('#isWhetherSign')) return false;
    if (!checkDropDownChoice('#isQuelificationCertificate')) return false;
    if (!checkDropDownChoice('#isGraduationCertificate')) return false;
    // if (!checkDropDownChoice('#isInformationCard')) return false;
    if (!checkDropDownChoice('#isGroupFiling')) return false;

    // 验证输入框
    if (!checkInputBox('[name="areaName"]', '请选择地区')) return false;
    if (!isFloatGteZeroByLength('#receiptPrice', 2, true, 8)) return false;
    if (!checkInputBox('#personalName')) return false;
    if (!isMobile('#personalPhone', true)) return false;
    if (!checkInputBox('#certificateName')) return false;
    if (!checkInputBox('#accountName')) return false;
    if (!checkInputBox('#accountBank')) return false;
    if (!isIdCardNo("#personalIdCard")) return false;
    if (!isWx('#personalWeixin')) return false;
    if (!regCheck(/^[0-9]\d*$/, '#accountNo', '请输入正确的银行卡号', true)) return false;
    if (!$("#certificateNo").val()) {
        DGG.Warning("证书编号不能为空");
        return false;
    }
    if (!checkCertificateNo("#certificateNo", 'GENERAL_CREDENTIAL', $('[name="id"]').val(), 1)) return false;
    return true;
}


/**
 * 费用申请
 * @param id
 * @param no
 */
function applyMoney(id, no) {
    // window.parent.updateTab("费用申请：" + no, orfApiUrl + "/orf/outlay/addoutlay.html?orderBusinessId=" + id + "&type=1");
    // 新的费用申请
    window.parent.updateTab('费用申请:' + no, orfNewApiUrl + "/outlay/apply_outlay.html");
}


/**
 * 资质详情页面跳转
 * @param no 资质编号
 * @param id 资质id
 */
function qualificationDetails(no, id) {
    window.top.addTab('资质详情:' + no, sysInfo.basePath + "/zs/credential/qualification/details_page.html?id=" + id);
}

/**
 * 删除销售子订单
 * @param orderBusinessId
 */
function delOrder(orderBusinessId, orderBusinessNo) {
    DGG.Confire('删除该销售子订单后，该子订单将无法新增证书！您确定删除编号为[' + orderBusinessNo + ']的销售子订单吗？', '操作提示', function () {
        DGG.loading();
        $.post(sysInfo.basePath + "/zs/general_credential/del_order_business.do", {orderBusinessId: orderBusinessId}, function (result) {
            if (result.code == 0) {
                DGG.Succeed('删除成功！');
                DGG.loading('close');
                search('#myTable', 'reload');
            } else {
                DGG.Errors(result.msg);
                search('#myTable', 'reload');
                DGG.loading('close');
            }
        })
    })
}